<template>
  <div>
    <!-- 头部导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体区域 -->
    <el-card class="box-card">
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="searchText" class="input-with-select" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"><el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button></el-col>
      </el-row>
      <!-- 用户信息区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column width="50px" type="index" label="#" :index="startnum" align="center"></el-table-column>
        <el-table-column prop="username" label="姓名" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center">
          <template slot-scope="scope">
            <el-form v-if="scope.row.id === currentId" :model="scope.row" :rules="userRules" ref="emailFormRef">
              <el-form-item prop="email">
                <el-input placeholder="请输入内容" v-model="scope.row.email" clearable></el-input>
              </el-form-item>
            </el-form>
            <span v-else>{{scope.row.email}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="电话" align="center">
          <template slot-scope="scope">
            <el-form v-if="scope.row.id === currentId" :model="scope.row" :rules="userRules" ref="mobileFormRef">
              <el-form-item prop="mobile">
                <el-input placeholder="请输入内容" v-model="scope.row.mobile" clearable></el-input>
              </el-form-item>
            </el-form>
            <span v-else>{{scope.row.mobile}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="角色" align="center">
          <template slot-scope="scope">
            <el-select v-model="roleId" placeholder="请选择" v-if="scope.row.id === currentSetId">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
                :disabled="roleId === item.id">
              </el-option>
            </el-select>
            <span v-else>{{scope.row.role_name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="isEdit?'保存':'编辑'" placement="top-end" :enterable="false">
              <el-button type="primary" :icon="isEdit?'el-icon-folder-checked':'el-icon-edit-outline'" size="mini" @click="editHandler(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top-end" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteHandler(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="设置" placement="top-end" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="settingHandler(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-sizes="[1, 2, 4, 8, 10]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加对话框区域 -->
    <el-dialog
      title="提示"
      :visible.sync="addUserDialogVisible"
      width="40%" :before-close="closeDialog">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="userForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="userSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getUserList()
    this.getRoleList()
  },
  data () {
    // 确认密码验证
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.userForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 电话号码验证
    let validateMobile = (rule, value, callback) => {
      let mobileExp = /^(0|86|19521)?(13[0-9]|14[579]|15[0-35-9]|166|17[0-8]|18[0-9]|19[1389])\d{8}$/
      if (!mobileExp.test(value)) {
        callback(new Error('请输入正确手机号'))
      } else {
        callback()
      }
    }
    // 邮箱验证
    let validateEmail = (rule, value, callback) => {
      let emailExp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-z0-9-_])+/
      if (!emailExp.test(value)) {
        callback(new Error('请输入合法邮箱'))
      } else {
        callback()
      }
    }
    return {
      userList: [],
      roleList: [],
      total: 0,
      pagenum: 1,
      pagesize: 4,
      searchText: '',
      // 是否编辑状态
      isEdit: false,
      currentId: undefined,
      // 是否设置状态
      isSetting: false,
      currentSetId: undefined,
      roleId: undefined,
      addUserDialogVisible: false,
      userForm: {
        username: '',
        email: '',
        mobile: '',
        password: '',
        checkPass: ''
      },
      userRules: {
        username: [
          {
            required: true, message: '请输入账号', trigger: 'blur'
          },
          {
            min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        checkPass: [
          {
            required: true, message: '请输入确认密码', trigger: 'blur'
          },
          { validator: validatePass, trigger: 'blur' }
        ],
        mobile: [
          {
            required: true, message: '请输入手机号码', trigger: 'blur'
          },
          { validator: validateMobile, trigger: 'blur' }
        ],
        email: [
          {
            required: true, message: '请输入邮箱', trigger: 'blur'
          },
          { validator: validateEmail, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    startnum () {
      return (this.pagenum - 1) * this.pagesize + 1
    }
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      let { data: res } = await this.$http.get('users', { params: { pagenum: this.pagenum, pagesize: this.pagesize, query: this.searchText } })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else if (res.data.users.length === 0) {
        this.pagenum -= 1
        this.getUserList()
      }
      this.userList = res.data.users
      // console.log(res.data.users)
      this.total = res.data.total
    },
    // 获取角色列表
    async getRoleList () {
      let { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.roleList = res.data
    },
    handleSizeChange (newPagesize) {
      this.pagesize = newPagesize
      this.getUserList()
    },
    handleCurrentChange (newPagenum) {
      this.pagenum = newPagenum
      this.getUserList()
    },
    async userStateChange (user) {
      let { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        this.userList.forEach((item, index) => {
          if (item.id === user.id) {
            item.mg_state = !user.mg_state
          }
        })
        return this.$message.error(res.meta.msg)
      }
      return this.$message.success(res.meta.msg)
    },
    closeDialog (done) {
      this.$refs.userFormRef.resetFields()
      done()
    },
    // 添加用户
    userSubmit () {
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return this.$message.error('用户信息有错误')
        let { data: res } = await this.$http.post('users', this.userForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$refs.userFormRef.resetFields()
        this.addUserDialogVisible = false
        this.getUserList()
      })
    },
    // 编辑动作处理
    async editHandler (user) {
      // console.log(user)
      if (!this.isEdit) {
        this.isEdit = !this.isEdit
        this.currentId = user.id
      } else {
        this.isEdit = !this.isEdit
        this.currentId = undefined
        this.$refs.emailFormRef.validate(emailValid => {
          if (!emailValid) {
            this.getUserList()
            return this.$message.error('邮箱信息错误')
          }
          this.$refs.mobileFormRef.validate(async mobileValid => {
            if (!mobileValid) {
              this.getUserList()
              return this.$message.error('手机号码错误')
            }
            let { data: res } = await this.$http.put(`users/${user.id}`, { email: user.email, mobile: user.mobile })
            this.getUserList()
            console.log(res)
            if (res.meta.status !== 200) {
              return this.$message.error(res.meta.msg)
            }
            return this.$message.success(res.meta.msg)
          })
        })
      }
    },
    // 删除动作处理
    async deleteHandler (id) {
      let status = await this.$confirm('你确定永久删除该用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (status !== 'confirm') return this.$message.error('已取消删除操作')
      let { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    // 设置动作处理
    async settingHandler (user) {
      // console.log(user.id, this.currentId, this.isSetting)
      if (!this.isSetting) {
        this.isSetting = !this.isSetting
        let { data: userData } = await this.$http.get(`users/${user.id}`)
        if (userData.meta.status !== 200) {
          return this.$message.error(userData.meta.msg)
        }
        this.roleId = userData.data.rid
        this.currentSetId = user.id
        return
      }
      // 防止点击其他行的按钮触发
      if (user.id !== this.currentSetId) {
        return this.$message.error('请点击正确的按钮保存')
      }
      this.isSetting = !this.isSetting
      this.currentSetId = undefined
      let { data: res } = await this.$http.put(`users/${user.id}/role`, { rid: this.roleId })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.getUserList()
      return this.$message.success(res.meta.msg)
    }
  }
}
</script>

<style lang="less" scoped>

</style>
